use crate::db::dao::te_policy_group::TePolicyGroupDao;
use crate::db::{dao, po};
use crate::dto;
use crate::service::Error;
use std::sync::Arc;
use wanmesh_common::error::ResponseError;

#[async_trait::async_trait]
pub trait TePolicyGroupService: Sync + Send {
    async fn add(
        &self,
        params: &dto::core::te_policy_group::AddParams,
    ) -> Result<dto::core::te_policy_group::AddResponseData, Error>;

    async fn list(
        &self,
        filter: &dto::core::te_policy_group::Filter,
        offset: u64,
        limit: u64,
    ) -> Result<Vec<dto::core::te_policy_group::TePolicyGroupItem>, Error>;

    async fn get(&self, te_policy_group_id: &str) -> Result<dto::core::te_policy_group::TePolicyGroupItem, Error>;

    async fn try_get(
        &self,
        te_policy_group_id: &str,
    ) -> Result<Option<dto::core::te_policy_group::TePolicyGroupItem>, Error>;

    async fn update(
        &self,
        te_policy_group_id: &str,
        params: &dto::core::te_policy_group::UpdateParams,
    ) -> Result<(), Error>;

    async fn delete(&self, te_policy_group_id: &str) -> Result<(), Error>;

    async fn count(&self, filter: &dto::core::te_policy_group::Filter) -> Result<u64, Error>;
}

pub struct DefaultTePolicyGroupService {
    te_policy_group_dao: Arc<dyn TePolicyGroupDao>,
}

impl DefaultTePolicyGroupService {
    pub fn new(te_policy_group_dao: Arc<dyn TePolicyGroupDao>) -> Self {
        Self { te_policy_group_dao }
    }
}

#[async_trait::async_trait]
impl TePolicyGroupService for DefaultTePolicyGroupService {
    async fn add(
        &self,
        params: &dto::core::te_policy_group::AddParams,
    ) -> Result<dto::core::te_policy_group::AddResponseData, Error> {
        let te_policy_group_id = wanmesh_common::util::new_id()?;

        self.te_policy_group_dao
            .insert(po::te_policy_group::ActiveModel {
                id: Default::default(),
                te_policy_group_id: po::ActiveValue::Set(te_policy_group_id.clone()),
                name: po::ActiveValue::Set(params.name.clone()),
                description: po::ActiveValue::Set(params.description.clone()),
                create_timestamp_millis: Default::default(),
                update_timestamp_millis: Default::default(),
            })
            .await?;

        Ok(dto::core::te_policy_group::AddResponseData { te_policy_group_id })
    }

    async fn list(
        &self,
        filter: &dto::core::te_policy_group::Filter,
        offset: u64,
        limit: u64,
    ) -> Result<Vec<dto::core::te_policy_group::TePolicyGroupItem>, Error> {
        let po_list = self
            .te_policy_group_dao
            .find(dao::FindParams {
                filter: filter.into(),
                offset: Some(offset),
                limit: Some(limit),
                ..Default::default()
            })
            .await?;

        let list = po_list.into_iter().map(|m| m.into()).collect();
        Ok(list)
    }

    async fn get(&self, te_policy_group_id: &str) -> Result<dto::core::te_policy_group::TePolicyGroupItem, Error> {
        let filter = dao::te_policy_group::Filter {
            te_policy_group_id: Some(te_policy_group_id.to_string()),
            ..Default::default()
        };

        if let Some(te_policy_group) = self.te_policy_group_dao.try_get(filter).await? {
            return Ok(te_policy_group.into());
        }

        Err(ResponseError::te_policy_group_not_found(te_policy_group_id).into())
    }

    async fn try_get(
        &self,
        te_policy_group_id: &str,
    ) -> Result<Option<dto::core::te_policy_group::TePolicyGroupItem>, Error> {
        let filter = dao::te_policy_group::Filter {
            te_policy_group_id: Some(te_policy_group_id.to_string()),
            ..Default::default()
        };

        if let Some(m) = self.te_policy_group_dao.try_get(filter).await? {
            return Ok(Some(m.into()));
        }

        Ok(None)
    }

    async fn update(
        &self,
        te_policy_group_id: &str,
        params: &dto::core::te_policy_group::UpdateParams,
    ) -> Result<(), Error> {
        if params == &Default::default() {
            return Ok(());
        }

        let filter = dao::te_policy_group::Filter {
            te_policy_group_id: Some(te_policy_group_id.to_string()),
            ..Default::default()
        };

        self.te_policy_group_dao.update(filter, params.into()).await?;

        Ok(())
    }

    async fn delete(&self, te_policy_group_id: &str) -> Result<(), Error> {
        let filter = dao::te_policy_group::Filter {
            te_policy_group_id: Some(te_policy_group_id.to_string()),
            ..Default::default()
        };

        self.te_policy_group_dao.delete(filter).await?;

        Ok(())
    }

    async fn count(&self, filter: &dto::core::te_policy_group::Filter) -> Result<u64, Error> {
        let count = self.te_policy_group_dao.count(filter.into()).await?;
        Ok(count)
    }
}

impl From<&dto::core::te_policy_group::Filter> for dao::te_policy_group::Filter {
    fn from(value: &dto::core::te_policy_group::Filter) -> Self {
        Self {
            te_policy_group_id: None,
            name: value.name.clone(),
            headend: value.headend.clone(),
            endpoint: value.endpoint.clone(),
        }
    }
}

impl From<dto::core::te_policy_group::Filter> for dao::te_policy_group::Filter {
    fn from(value: dto::core::te_policy_group::Filter) -> Self {
        Self::from(&value)
    }
}

impl From<&dto::core::te_policy_group::UpdateParams> for dao::te_policy_group::UpdateParams {
    fn from(value: &dto::core::te_policy_group::UpdateParams) -> Self {
        Self {
            name: po::option_to_active_value(value.name.clone()),
            description: po::option_to_active_value(value.description.clone()),
        }
    }
}

impl From<&po::te_policy_group::Model> for dto::core::te_policy_group::TePolicyGroupItem {
    fn from(value: &po::te_policy_group::Model) -> Self {
        Self {
            te_policy_group_id: value.te_policy_group_id.clone(),
            inner: dto::core::te_policy_group::TePolicyGroup {
                name: value.name.clone(),
                description: value.description.clone(),
            },
        }
    }
}

impl From<po::te_policy_group::Model> for dto::core::te_policy_group::TePolicyGroupItem {
    fn from(value: po::te_policy_group::Model) -> Self {
        Self::from(&value)
    }
}
